package com.rio.helper.file;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.annotation.SuppressLint;

public class UploadTask {

	private String mFileName = "";
	private String mFilePath = "";
	private String mUrl = "";
	private UploadListener mListener;
	private int current;
	private long mTotal;
	
	@SuppressLint("NewApi")
	public UploadTask(String url, File target,
			UploadListener listener) {
		mTotal =target.getTotalSpace();
		mFileName = target.getName();
		mFilePath = target.getAbsolutePath();
		mUrl = url;
		mListener = listener;
		uploadFile();
	}

	/* 上传文件至Server的方法 */
	private void uploadFile() {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		try {
			if(mListener != null)mListener.onReady();
			URL url = new URL(mUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			/* 允许Input、Output，不使用Cache */
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 设置传送的method=POST */
			con.setRequestMethod("POST");
			/* setRequestProperty */
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			/* 设置DataOutputStream */
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; "
					+ "name=\"file1\";filename=\"" + mFileName + "\"" + end);
			ds.writeBytes(end);
			/* 取得文件的FileInputStream */
			FileInputStream fStream = new FileInputStream(mFilePath);
			/* 设置每次写入1024bytes */
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			/* 从文件读取数据至缓冲区 */
			while ((length = fStream.read(buffer)) != -1) {
				/* 将资料写入DataOutputStream中 */
				ds.write(buffer, 0, length);
				current += length;
				if(mListener != null)mListener.onBytesCopied(current,mTotal);
			}
			ds.writeBytes(end);
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			/* close streams */
			fStream.close();
			ds.flush();
			/* 取得Response内容 */
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			/* 将Response显示于Dialog */
			if(mListener != null)mListener.onComplete();
			/* 关闭DataOutputStream */
			ds.close();
		} catch (Exception e) {
			if(mListener != null)mListener.onFail(e,current);
		}
	}

	/** Listener and controller for copy process */
	public interface UploadListener {
		/**
		 * @param current
		 *            Loaded bytes
		 * @param total
		 *            Total bytes for loading
		 * @return <b>true</b> - if copying should be continued; <b>false</b> -
		 *         if copying should be interrupted
		 */
		void onBytesCopied(int current, long total);

		/**
		 * @param e
		 * @param target
		 */
		void onFail(Exception e,int current);

		/**
		 * @param url
		 * @param target
		 */
		void onComplete();

		void onReady();

	}

}
